<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$servername = "localhost";
$username = "root"; // 数据库用户名
$password = "store"; // 数据库密码
$dbname = "aiweb"; // 数据库名称

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取表单数据
    $name = $_POST['name'];
    $type = $_POST['type'];
    $info = $_POST['info'];
    $details = $_POST['details'];
    $url = $_POST['url'];

    // 处理文件上传
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == UPLOAD_ERR_OK) {
        $logo = $_FILES['logo'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];  // 允许的文件类型
        $upload_dir = 'uploads/';  // 设置上传目录

        // 检查文件类型
        if (in_array($logo['type'], $allowed_types)) {
            // 生成唯一的文件名
            $logo_name = uniqid('logo_', true) . '.' . pathinfo($logo['name'], PATHINFO_EXTENSION);
            $logo_path = $upload_dir . $logo_name;

            // 确保上传目录存在
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            // 移动上传文件到指定目录
            if (move_uploaded_file($logo['tmp_name'], $logo_path)) {
                // 获取图片的 URL
                $logo_url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $logo_path;

                // 插入数据到数据库
                $sql = "INSERT INTO app (appname, type, info, details, logo, url) VALUES ('$name', '$type', '$info', '$details', '$logo_url', '$url')";

                if ($conn->query($sql) === TRUE) {
                    $message = "新应用添加成功！";
                } else {
                    $message = "错误: " . $conn->error;
                }
            } else {
                $message = "文件上传失败，请重试。";
            }
        } else {
            $message = "只允许上传 JPEG、PNG 或 GIF 格式的图片。";
        }
    } else {
        $message = "请上传应用的logo。";
    }

    // 使用 JavaScript alert 提示信息并跳转页面
    echo "<script>alert('$message');window.location.href='pages/add-page.php';</script>";
}

$conn->close();
?>
